
package com.hlkj.pay.app.common.ext.qiniu;

import com.google.gson.Gson;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.common.OssExtPt;
import com.hlkj.pay.app.common.ext.CommonExtConstant;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.dto.common.StorageConfig;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 七牛云存储
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = CommonExtConstant.CHANNEL_QINIU)
public class QiniuOssExtPt implements OssExtPt {

    /**
     * 鉴权令牌
     *
     * @author fzr
     * @return String
     */
    public String upToken(StorageConfig storageConfig) {
        String accessKey = storageConfig.getAccessKey();
        String secretKey = storageConfig.getSecretKey();
        String bucket = storageConfig.getBucket();
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucket);
    }

    /**
     * 上传文件
     *
     * @author fzr
     * @param multipartFile
     *            文件对象
     * @param key
     *            保存文件的名称
     */
    public String upload(MultipartFile multipartFile, String key, StorageConfig storageConfig) throws IOException {
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Response response = uploadManager.put(multipartFile.getBytes(), key, this.upToken(storageConfig));
        new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return storageConfig.getDomain() + key;
    }

    @Override
    public String upload(MultipartFile multipartFile, CommonEnum.OssEnum ossEnum, String key, StorageConfig storageConfig) throws IOException {
        return upload(multipartFile, ossEnum.getFolder() + "/" + key, storageConfig);
    }

    @Override
    public String upload(byte[] fileArray, CommonEnum.OssEnum ossEnum, String key, StorageConfig storageConfig) throws IOException {
        key = ossEnum.getFolder() + "/" + key;
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Response response = uploadManager.put(fileArray, key, this.upToken(storageConfig));
        new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return storageConfig.getDomain() + key;
    }

    @Override
    public String uploadZip(List<String> fileList, CommonEnum.OssEnum ossEnum, String key, StorageConfig storageConfig) throws IOException {
        return "";
    }
}
